import { ref } from 'vue'
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
import { ElMessage } from 'element-plus'

interface ApiResponse<T = any> {
  code: number
  message: string
  data: T
}

export function useApi() {
  const loading = ref(false)
  const error = ref<string | null>(null)

  // 创建axios实例
  const api: AxiosInstance = axios.create({
    baseURL: '/api',
    timeout: 10000,
    headers: {
      'Content-Type': 'application/json',
    },
  })

  // 请求拦截器
  api.interceptors.request.use(
    (config) => {
      loading.value = true
      error.value = null
      
      // 添加token到请求头
      const token = localStorage.getItem('token')
      if (token) {
        config.headers.Authorization = `Bearer ${token}`
      }
      
      return config
    },
    (err) => {
      loading.value = false
      error.value = err.message
      return Promise.reject(err)
    }
  )

  // 响应拦截器
  api.interceptors.response.use(
    (response: AxiosResponse<ApiResponse>) => {
      loading.value = false
      
      // 如果响应码不是200，显示错误信息
      if (response.data.code !== 200) {
        ElMessage.error(response.data.message || '请求失败')
        return Promise.reject(new Error(response.data.message || '请求失败'))
      }
      
      return response
    },
    (err) => {
      loading.value = false
      error.value = err.message
      
      // 处理不同的错误状态码
      if (err.response) {
        switch (err.response.status) {
          case 401:
            ElMessage.error('未授权，请重新登录')
            localStorage.removeItem('token')
            window.location.href = '/login'
            break
          case 403:
            ElMessage.error('权限不足')
            break
          case 404:
            ElMessage.error('请求的资源不存在')
            break
          case 500:
            ElMessage.error('服务器内部错误')
            break
          default:
            ElMessage.error(err.response.data?.message || '请求失败')
        }
      } else if (err.request) {
        ElMessage.error('网络连接失败，请检查网络设置')
      } else {
        ElMessage.error(err.message || '请求失败')
      }
      
      return Promise.reject(err)
    }
  )

  // 封装请求方法
  const request = async <T = any>(
    config: AxiosRequestConfig
  ): Promise<ApiResponse<T>> => {
    try {
      const response = await api.request(config)
      return response.data
    } catch (err) {
      throw err
    }
  }

  // GET请求
  const get = async <T = any>(url: string, params?: any): Promise<ApiResponse<T>> => {
    return request<T>({
      method: 'GET',
      url,
      params,
    })
  }

  // POST请求
  const post = async <T = any>(url: string, data?: any): Promise<ApiResponse<T>> => {
    return request<T>({
      method: 'POST',
      url,
      data,
    })
  }

  // PUT请求
  const put = async <T = any>(url: string, data?: any): Promise<ApiResponse<T>> => {
    return request<T>({
      method: 'PUT',
      url,
      data,
    })
  }

  // DELETE请求
  const del = async <T = any>(url: string): Promise<ApiResponse<T>> => {
    return request<T>({
      method: 'DELETE',
      url,
    })
  }

  return {
    loading,
    error,
    api,
    request,
    get,
    post,
    put,
    delete: del,
  }
} 